/// <reference types="node" />
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import ElementPlus from "unplugin-element-plus/vite"; // 不加这个配置，ElMessage出不来
import { join } from "node:path";

const port = 7777;

function resolve(dir: string) {
  return join(__dirname, dir);
}
const root = resolve("src");
// https://vitejs.dev/config/
export default defineConfig(({ command }) => {
  return {
    root,
    resolve: {
      alias: {
        "@src": root,
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    base: "/", // 这里更改打包相对绝对路径

    build: {
      rollupOptions: {
        output: {
          // 在这里修改静态资源路径
          chunkFileNames: "worker/assets/js/[name]-[hash].js",
          entryFileNames: "worker/assets/js/[name]-[hash].js",
          // assetFileNames: 'work/assets/[ext]/[name]-[hash].[ext]',
          assetFileNames(assetInfo) {
            const imgExts = [".png", ".jpg", ".jpeg", ".ico", ".svg", "gif"];
            if (imgExts.some((ext) => assetInfo.name?.endsWith(ext))) {
              return "worker/assets/imgs/[name]-[hash].[ext]";
            }
            return "worker/assets/css/[name]-[hash].[ext]";
          },
        },
      },
    },
    server:
      command === "build"
        ? undefined
        : {
            port: 1234,
          },
    plugins: [
      vue(),
      // 按需引入，主题色的配置，需要加上 importStyle: 'sass'
      AutoImport({
        resolvers: [ElementPlusResolver()],
        dts: resolve(`custom-types/auto-imports.d.ts`),
        imports: ["vue"],
      }),
      Components({
        dirs: [resolve("src/view"), resolve("src/components")],
        resolvers: [
          ElementPlusResolver({
            importStyle: "sass",
          }),
          AntDesignVueResolver({ importStyle: false, resolveIcons: true }),
        ],
        dts: resolve(`custom-types/components.d.ts`),
      }),
      ElementPlus({}),
    ],

    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "src/styles/element/index.scss" as *; @use "src/styles/mixins.scss" as *; @use "src/styles/variables.scss" as *;`,
        },
      },
    },
    // 是否压缩代码
    minify: true,
    // 是否生成sourceMap
    sourceMap: true,

    preview: {
      // host: '192.168.123.204',
      host: "0.0.0.0",
      port: port,
    },
  };
});
